<template>
  <div class="main">
    <div class="title">
      <!-- WeSlots,<br />welcome! -->
      <!-- <img src="@/assets/img/bannerIcon.png" alt="" @click="$router.push('/')"> -->
      <img
        src="@/assets/img/bannerIcon.png"
        alt=""
        @click="goToHomeWithInviteCode"
      />
    </div>

    <div class="cont">
      <div class="login-type-box">
        <div
          class="lable"
          :style="selectType === 'email' ? 'color: #ffff' : ''"
          @click="selectType = 'email'"
        >
          {{ $t("Email") }}
        </div>
        <!-- <div class="lable" :style="selectType === 'mobile' ? 'color: #ffff' : ''" @click="selectType = 'mobile'">Telepon
        </div> -->
      </div>
      <div class="item phonbox" v-if="selectType === 'email'">
        <div class="p-l email-p-l">
          <van-icon name="envelop-o" class="email-icon" />
        </div>
        <input
          :placeholder="$t('Email')"
          @input="inputValueChange"
          v-model="email"
        />
      </div>

      <div class="item phonbox" v-else>
        <div class="p-l" @click="goPhoneNumber">
          <img class="phone-icon" src="@/assets/img/phoneNumber.png" />
          <div class="phone-qu">
            <van-loading size="24" v-if="!areaCode" />{{ areaCode }}
          </div>
          <img class="select-icon" src="@/assets/img/select-right.png" />
        </div>
        <input
          type="text"
          :placeholder="$t('NomorTelepon')"
          :disabled="!areaCode"
          v-model="mobile"
          @input="inputValueChange"
          @keyup="mobile = mobile.replace(/[^\d]/g, '')"
          @afterpaste="mobile = mobile.replace(/[^\d]/g, '')"
        />
      </div>

      <!-- <div class="item codebox">
        <div class="code-l">
          <div class="p-l">
            <img class="icon" src="@/assets/img/bancein.png" />
          </div>
          <input
            type="text"
            :placeholder="$t('Code')"
            v-model="code"
            @input="inputValueChange"
          />
        </div>
        <div
          :class="['code-r', { active: (mobile || email) && !time }]"
          @click="sendSMS"
        >
          <template v-if="!time">{{ $t("GetCode") }}</template>
          <template v-if="time">{{ time }}s</template>
        </div>
      </div> -->

      <div class="item">
        <div class="p-l">
          <img class="icon" src="@/assets/img/lock.png" />
        </div>
        <input
          type="password"
          :class="{ active: password.trim() }"
          v-model="password"
          @input="inputValueChange"
          :placeholder="$t('SetPassword')"
          @blur="passwordVilidate"
        />
      </div>

      <div class="item">
        <div class="p-l">
          <img class="icon" src="@/assets/img/lock.png" />
        </div>
        <input
          type="password"
          :class="{ active: newPassword.trim() }"
          v-model="newPassword"
          @input="inputValueChange"
          :placeholder="$t('SetResetPassword')"
        />
      </div>

      <div class="item">
        <div class="p-l">
          <img class="icon" src="@/assets/img/auic1.png" />
        </div>
        <input v-model="invitationCode" :placeholder="$t('InvitationCode')" />
      </div>

      <div :class="['loginbtn', { disabled: disabled }]" @click="register">
        <div :class="['lbcenter', { disabled: disabled }]">
          {{ $t("Register") }}
        </div>
      </div>
      <div class="btnlist">
        <div class="bl-l"></div>
        <div class="bl-r" @click="$router.push('/login')">
          {{ $t("ToLogin") }}
        </div>
      </div>

      <div class="querybox">
        <div class="query-checked" @click="isAgree = !isAgree">
          <span v-if="isAgree">√</span>
        </div>
        <div class="query-text" style="color: white">
          {{ $t("AgreeWith") }} "<span
            @click="$router.push('/serviceAgreement')"
            >{{ $t("ServiceAgreement") }}</span
          >" {{ $t("dan") }} "<span @click="$router.push('/privacyPolicy')">{{
            $t("PrivacyPolicy")
          }}</span
          >"
        </div>
      </div>
    </div>

    <van-popup v-model="popShow" round>
      <div class="popbox">
        <div class="tbc">
          <input
            type="text"
            v-model="txCode"
            :placeholder="$t('txCodeVertical')"
          />
          <canvas id="canvas" @click="draw()"></canvas>
        </div>
        <div class="querybtn" @click="txCodeVi">{{ $t("Confirm") }}</div>
      </div>
    </van-popup>
  </div>
</template>
<script
  async
  defer
  crossorigin="anonymous"
  src="https://connect.facebook.net/en_US/sdk.js"
></script>
<script>
import {
  httpIpLocation,
  httpGetPhoneAreaCode,
  httpSmsSend,
  httpEmailSend,
  httpMobileRegister,
  httpInfo,
} from "@/http/api";

import { phoneGetCodeNum, phoneSetCodeNum } from "@/utils/common";

export default {
  name: "register",
  data() {
    return {
      email: "",
      selectType: "email",
      phoneAreaList: [], // 国家区号
      areaCode: localStorage.getItem("areaCode") || "", //区号
      mobile: "", //手机号
      code: "", //验证码
      password: "", //密码
      newPassword: "", //再次输入密码
      invitationCode: this.$route.query.invite_code || "", //邀请码
      time: 0, // 倒计时
      isAgree: false, //是否同意协议
      registerAjax: false,

      popShow: false,
      txCode: "",
      show_num: [],
      disabled: true,
    };
  },
  created() {
    if (!this.areaCode) this.getHttpGetPhoneAreaCode();
    if (localStorage.getItem("TOKEN")) this.$router.push("/");
    if (this.$route.query.selectType == "mobile") {
      this.selectType = "mobile";
    }
  },
  methods: {
    goToHomeWithInviteCode() {
      // 获取浏览器 URL 中的参数 invite_code
      const urlParams = new URLSearchParams(window.location.search);
      const inviteCode = urlParams.get("invite_code");

      // 构建首页的路径，并将 invite_code 作为参数传递
      const homePath = { path: "/", query: { invite_code: inviteCode } };

      // 使用 $router.push 导航到首页
      this.$router.push(homePath);
    },

    // 获取手机区号,所属国家
    async getHttpGetPhoneAreaCode() {
      let res = await httpGetPhoneAreaCode();
      console.log(res);
      if (res.code == 0) {
        this.phoneAreaList = res.data || [];
      }
      this.areaCode = "+62";
      // this.getHttpIpLocation();
    },
    // 获取当前ip信息
    async getHttpIpLocation() {
      let res = await httpIpLocation();
      console.log(res);
      if (res.code == 0) {
        let country = res.data?.country || "";
        this.phoneAreaList.forEach((v) => {
          if (v.country == country) this.areaCode = v.area_code;
        });
        if (!this.areaCode) this.areaCode = "+62";
      }
    },
    // 发送验证码
    async sendSMS() {
      if (this.time) return;
      if (!this.mobile && !this.email)
        return this.$Toast(this.$t("phoneOrEmailTips"));
      this.time = 60;
      let timer = setInterval(() => {
        this.time -= 1;
        if (this.time <= 0) {
          this.time = 0;
          clearInterval(timer);
        }
      }, 1000);

      let res;
      if (this.selectType === "mobile") {
        let params = {
          mobile_area_code: this.areaCode,
          mobile: this.mobile,
          code_type: "register",
          timestamp: Math.floor(Date.now() / 1000),
        };
        res = await httpSmsSend(params);
      } else {
        let params = { email: this.email, code_type: "register" };
        res = await httpEmailSend(params);
      }
      if (res.code == 0) {
        this.$Toast.success(this.$t("Success"));
        if (this.selectType === "mobile") {
          phoneSetCodeNum("register", this.mobile);
        }
      } else {
        this.time = 0;
        clearInterval(timer);
        this.$Toast(res.msg);
      }
    },
    inputValueChange() {
      if (
        (this.mobile.trim() || this.email) &&
        this.password.trim() &&
        this.newPassword.trim()
        //  &&this.code.trim()
      )
        this.disabled = false;
      else this.disabled = true;
    },
    // 密码验证
    passwordVilidate(pwd) {
      if (pwd.length < 8 || pwd.length > 16) {
        return this.$Toast.fail(this.$t("passwordVertical"));
      }
    },
    // 注册
    async register() {
      if (this.registerAjax) return;
      if (this.disabled) return;
      if (!this.mobile.trim() && !this.email)
        return this.$Toast.fail(this.$t("phoneOrEmailTips"));
      // if (!this.code.trim()) return this.$Toast.fail(this.$t("codeVertical")); //验证码
      if (!this.password.trim())
        return this.$Toast.fail(this.$t("SetPassword")); //请输入密码
      if (this.password.length < 8 || this.password.length > 16) {
        return this.$Toast.fail(this.$t("passwordVertical"));
      }
      if (!this.newPassword.trim())
        return this.$Toast.fail(this.$t("SetPasswordAgain")); //请再次输入密码
      if (this.password.trim() != this.newPassword.trim())
        return this.$Toast.fail(this.$t("inconsistent")); //两次密码不一致
      // if (!this.invitationCode.trim()) return this.$Toast.fail("请输入邀请码");
      if (!this.isAgree) return this.$Toast.fail(this.$t("agreePrivacyPolicy")); //同意协议

      let params = {
        mobile_area_code: this.areaCode,
        account_name: this.selectType === "mobile" ? this.mobile : this.email,
        password: this.password,
        again_password: this.newPassword,
        code: this.code,
        invite_code: this.invitationCode,
        type: this.selectType,
      };
      this.registerAjax = true;
      fbq("track", "CompleteRegistration"); //注册
      let res = await httpMobileRegister(params);
      if (res.code == 0) {
        this.$Toast.success(this.$t("Success"));
        if (res.code == 0) {
          localStorage.setItem("TOKEN", res.data.token);
          fbq("track", "Lead"); //注册成功
          // 获取用户信息
          let res2 = await httpInfo();
          if (res2.code == 0) {
            localStorage.setItem("mobile", this.mobile);
            localStorage.setItem("email", this.email);
            localStorage.setItem("areaCode", this.areaCode);
            localStorage.setItem("account_name", res2.data.account_name);
            localStorage.setItem("invite_code", res2.data.invite_code);
            localStorage.setItem("uid", res2.data.uid);

            this.$router.push("/");
          }
        }
      } else {
        this.$Toast.fail(res.message);
      }
      this.registerAjax = false;
    },
    goPhoneNumber() {
      if (!this.areaCode) return;
      this.$router.push({
        name: `phoneNumber`,
        query: {
          selectType: this.selectType,
          type: 2,
        },
      });
    },

    sendSMSbefore() {
      if (!this.mobile && !this.email)
        return this.$Toast(this.$t("phoneOrEmailTips"));

      if (this.selectType === "mobile") {
        let num = phoneGetCodeNum("register", this.mobile);
        if (num >= 3 && num < 5) {
          this.$Toast(
            `${this.$t("numberSent")} ${5 - num} ${this.$t("times")}`
          );
        } else if (num > 4) {
          return this.$Toast(this.$t("limits"));
        }
      }

      this.popShow = true;
      setTimeout(() => this.draw(), 200);
    },

    // 生成图片验证码
    draw() {
      let canvas = document.getElementById("canvas"); //获取到canvas的对象，演员
      let canvas_width = canvas.offsetWidth;
      let canvas_height = canvas.offsetHeight;

      let context = canvas.getContext("2d"); //获取到canvas画图的环境，演员表演的舞台
      canvas.width = canvas_width;
      canvas.height = canvas_height;
      let sCode =
        "a,b,c,d,e,f,g,h,i,j,k,m,n,p,q,r,s,t,u,v,w,x,y,z,A,B,C,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0";
      let aCode = sCode.split(",");
      let aLength = aCode.length; //获取到数组的长度

      for (let i = 0; i < 4; i++) {
        //这里的for循环可以控制验证码位数（如果想显示6位数，4改成6即可）
        let j = Math.floor(Math.random() * aLength); //获取到随机的索引值
        // let deg = Math.random() * 30 * Math.PI / 180;//产生0~30之间的随机弧度
        let deg = Math.random() - 0.5; //产生一个随机弧度
        let txt = aCode[j]; //得到随机的一个内容
        this.show_num[i] = txt.toLowerCase();
        let x = 10 + i * 20; //文字在canvas上的x坐标
        let y = 20 + Math.random() * 8; //文字在canvas上的y坐标
        context.font = "bold 23px 微软雅黑";

        context.translate(x, y);
        context.rotate(deg);

        context.fillStyle = this.randomColor();
        context.fillText(txt, 0, 0);

        context.rotate(-deg);
        context.translate(-x, -y);
      }
      for (let i = 0; i <= 5; i++) {
        //验证码上显示线条
        context.strokeStyle = this.randomColor();
        context.beginPath();
        context.moveTo(
          Math.random() * canvas_width,
          Math.random() * canvas_height
        );
        context.lineTo(
          Math.random() * canvas_width,
          Math.random() * canvas_height
        );
        context.stroke();
      }
      for (let i = 0; i <= 30; i++) {
        //验证码上显示小点
        context.strokeStyle = this.randomColor();
        context.beginPath();
        let x = Math.random() * canvas_width;
        let y = Math.random() * canvas_height;
        context.moveTo(x, y);
        context.lineTo(x + 1, y + 1);
        context.stroke();
      }
    },

    randomColor() {
      let r = Math.floor(Math.random() * 256);
      let g = Math.floor(Math.random() * 256);
      let b = Math.floor(Math.random() * 256);
      return "rgb(" + r + "," + g + "," + b + ")";
    },
    txCodeVi() {
      if (this.txCode.toLowerCase() == this.show_num.join("")) {
        this.popShow = false;
        this.sendSMS();
      } else {
        this.$Toast(this.$t("codeError"));
        this.draw();
      }
    },
  },
};
</script>

<style lang="less" scoped>
.main {
  min-height: 100vh;
  //background: #eee;
  width: 100%;
  padding-bottom: 20px;
  color: #fff;

  .login-type-box {
    display: flex;
  }

  .lable {
    font-size: 24px;
    color: rgba(171, 182, 212, 1);
    margin-bottom: 16px;
    margin-right: 10px;
  }

  .title {
    text-align: center;
    padding-top: 150px;
    font-size: 80px;
    font-weight: 700;
    color: rgba(112, 126, 162, 1);
    margin-bottom: 50px;

    img {
      width: 200px;
      height: 200px;
      display: inline-block;
    }
  }

  .cont {
    width: 100%;
    padding: 0 65px;

    .item {
      width: 100%;
      height: 94px;
      background: rgba(246, 247, 252, 1);
      display: flex;
      align-items: center;
      margin-bottom: 40px;
      padding-left: 30px;
      border-radius: 20px;

      .email-p-l {
        width: 60px !important;
      }

      .p-l {
        width: 60px;
        height: 38px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-right: 1px solid rgba(221, 228, 243, 1);
        flex-shrink: 0;

        .email-icon {
          color: rgba(171, 182, 212, 1);
        }

        .icon {
          width: 38px;
          height: 38px;
        }
      }

      &.phonbox {
        .p-l {
          width: 160px;
          height: 38px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          border-right: 1px solid rgba(221, 228, 243, 1);
          flex-shrink: 0;

          .phone-icon {
            width: 38px;
            height: 38px;
          }

          .select-icon {
            width: 40px;
            height: 40px;
          }

          .phone-qu {
            font-size: 24px;
            color: rgba(112, 126, 162, 1);
          }
        }
      }

      &.codebox {
        background: transparent;
        padding: 0;
        justify-content: space-between;

        .code-l {
          width: 292px;
          height: 94px;
          background: rgba(246, 247, 252, 1);
          display: flex;
          align-items: center;
          border-radius: 20px;
          padding-left: 30px;

          input {
            width: 180px;
            padding-right: 20px;
          }
        }

        .code-r {
          font-size: 30px;
          color: rgba(255, 255, 255, 1);
          width: 302px;
          height: 94px;
          opacity: 1;
          background: #dfe6fc;
          //background: rgba(196, 208, 248, 1);
          display: flex;
          align-items: center;
          justify-content: center;
          user-select: none;
          border-radius: 20px;

          &.active {
            background: url("~@/assets/img/19.png") center/100% 100% no-repeat;
            //background: rgb(72, 113, 248);
          }
        }
      }
    }

    input {
      padding-left: 24px;
      border: none;
      flex: 1;
      outline: none;
      font-size: 28px;
      font-weight: 700;
      color: rgba(132, 144, 177, 1);
      background: transparent;

      &::-webkit-input-placeholder {
        color: rgba(171, 182, 212, 1);
        font-size: 24px;
        font-weight: 400;
      }

      &.active {
        font-size: 40px;
        line-height: 38px;
        letter-spacing: 5px;
        height: 38px;
        max-width: 520px;
      }
    }

    .loginbtn {
      text-shadow: 1px 3px 1px 0px rgba(212, 161, 110, 0.88);
      font-size: 30px;
      font-weight: 700;
      letter-spacing: 2.4px;
      color: rgba(255, 255, 255, 1);
      display: flex;
      align-items: center;
      justify-content: center;
      width: 618px;
      height: 112px;
      opacity: 1;
      /**background: linear-gradient(
        178.44deg,
        rgba(255, 255, 255, 1) 0%,
        rgba(255, 226, 196, 1) 100%
      );
      box-shadow: 0px 7px 9px 0px rgba(201, 173, 144, 0.33);**/
      border-radius: 24px;
      background: url("~@/assets/img/19.png") center/100% 100% no-repeat;
      margin-bottom: 52px;

      &.disabled {
        background: #dfe6fc;
        box-shadow: 1px 7px 8px 0px rgba(201, 173, 144, 0);
        color: #ccc;
      }

      .lbcenter {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 594px;
        height: 88px;
        opacity: 1;
        /**background: linear-gradient(
          178.44deg,
          rgba(238, 220, 201, 1) 0%,
          rgba(220, 188, 155, 1) 100%
        );
        box-shadow: 1px 7px 8px 0px rgba(201, 173, 144, 0.51),
          inset 0px 3px 9px 0px rgba(197, 146, 92, 1);
        border-radius: 24px;**/

        user-select: none;

        &.disabled {
          background: #dfe6fc;
          box-shadow: 1px 7px 8px 0px rgba(201, 173, 144, 0);
          color: #ccc;
        }
      }
    }

    .btnlist {
      display: flex;
      width: 100%;
      justify-content: space-between;
      align-items: center;
      font-size: 28px;
      user-select: none;
      margin-bottom: 48px;

      .bl-l {
        color: rgba(210, 170, 127, 1);
      }

      .bl-r {
        // color: rgba(132, 144, 177, 1);
        color: #fff;
      }
    }

    .querybox {
      width: 100%;
      display: flex;
      align-items: center;

      .query-checked {
        width: 66px;
        height: 66px;
        background: rgba(246, 247, 252, 0.64);
        border: 2px solid rgba(255, 255, 255, 1);
        flex-shrink: 0;
        margin-right: 34px;
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 40px;
        font-weight: 600;
        color: rgba(112, 126, 162, 1);
      }

      .query-text {
        font-size: 28px;
        font-weight: 400;
        letter-spacing: 0px;
        color: rgb(126, 137, 169);
        line-height: 1.5;

        span {
          text-decoration: underline;
        }
      }
    }
  }
}

.popbox {
  width: 90vw;
  overflow: hidden;
  padding: 50px 30px 40px;

  .tbc {
    width: 100%;
    display: flex;
    align-items: center;

    input {
      padding: 24px;
      border: 1px solid #ccc;
      flex: 1;
      outline: none;
      font-size: 28px;
      width: 350px;
      margin-right: 20px;
      font-weight: 700;
      color: rgba(132, 144, 177, 1);
      background: transparent;
      border-radius: 10px;

      &::-webkit-input-placeholder {
        color: rgba(171, 182, 212, 1);
        font-size: 24px;
        font-weight: 400;
      }
    }

    #canvas {
      width: 200px;
      height: 80px;
    }
  }

  .querybtn {
    width: 100%;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 60px;
    background: linear-gradient(
      178.44deg,
      rgba(238, 220, 201, 1) 0%,
      rgba(220, 188, 155, 1) 100%
    );
    box-shadow: 1px 7px 8px 0px rgba(201, 173, 144, 0.51);
    border-radius: 40px;
    color: #fff;
    font-size: 40px;
    user-select: none;
  }
}
</style>
